package com.example.tccdemo.service;

import com.example.tccdemo.db131.dao.AccountAMapper;
import com.example.tccdemo.db131.model.AccountA;
import com.example.tccdemo.db132.dao.AccountBMapper;
import com.example.tccdemo.db132.model.AccountB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @describte:TODO
 * @program:distribute-transaction
 * @author:zhengdp
 * @create:2021-09-26 17:48:37
 **/
@Service
public class AccountService {
    @Autowired
    private AccountAMapper accountAMapper;
    @Autowired
    private AccountBMapper accountBMapper;

    // 指定事务管理器
    @Transactional(transactionManager = "tm131")
    public void transferAccount(){

        AccountA accountA = accountAMapper.selectByPrimaryKey(1);
        accountA.setBalance(accountA.getBalance().subtract(new BigDecimal(200)));
        accountAMapper.updateByPrimaryKey(accountA);

        try{
            AccountB accountB = accountBMapper.selectByPrimaryKey(2);
            accountB.setBalance(accountB.getBalance().add(new BigDecimal(200)));
            accountBMapper.updateByPrimaryKey(accountB);
            int i = 1/0;
        }catch (Exception e){
            // 事务补偿,一般是要精准捕获，不同异常使用不同的补偿
            // 在补偿过程中，出现错误，如何处理？
            AccountB accountB = accountBMapper.selectByPrimaryKey(2);
            accountB.setBalance(accountB.getBalance().subtract(new BigDecimal(200)));
            accountBMapper.updateByPrimaryKey(accountB);
            throw  e;
        }

    }
}
